package jEDF.PreciseScoring;

import java.awt.*;
import java.awt.event.*;
import java.io.*;

import javax.swing.*;

import jEDF.EDF.*;
import jEDF.Exceptions.*;
import jEDF.JEDF.*;

/**
 *
 * <p>Titre : jEDF</p>
 * <p>Description : Java European Data Format Viewer and Analyser</p>
 * <p>Author : Nizar Kerkeni</p>
 * <p>Copyright : Copyright (c) 2003-2006</p>
 * <p>Version 2.0</p>
 */

public class NewPreciseScoringDialog extends JDialog {
    private PreciseScoring preciseScoring = null;
    private JTabbedPane jTabbedPane = new JTabbedPane();

    private JEDFMainWindow mainWindow = null;

    private JButton jbNewCancel = new JButton(JEDFMainWindow.getLocalizedString("Cancel"));
    private JButton jbLoadCancel = new JButton(JEDFMainWindow.getLocalizedString("Cancel"));

    private JPanel loadPanel = new JPanel(new BorderLayout());
    private JLabel jlLoad = new JLabel(JEDFMainWindow.getLocalizedString(
            "Please choose the file you want to load."));
    private JTextField jtfLoad = new JTextField();
    private JButton jbLoadBrowse = new JButton(JEDFMainWindow.getLocalizedString("Browse"));
    private JButton jbLoadOk = new JButton(JEDFMainWindow.getLocalizedString("OK"));

    private JPanel newPanel = new JPanel(new BorderLayout());
    private JLabel jlNew = new JLabel(JEDFMainWindow.getLocalizedString(
            "Please choose the file you want to save to."));
    private JLabel jlNewGranularity = new JLabel(JEDFMainWindow.getLocalizedString(
            "Please choose the wanted granularity, in seconds :"));
    private JTextField jtfNewFileName = new JTextField();
    private JTextField jtfNewGranularity = new JTextField();
    private JButton jbNewBrowse = new JButton(JEDFMainWindow.getLocalizedString("Browse"));
    private JButton jbNewOk = new JButton("OK");

    /**
     * @param mainWindow the parent window
     * @param preciseScoring the PreciseScoring to set up
     * @param isLoading true to display the "Load" pane, false for the "New" pane
     */
    public NewPreciseScoringDialog(JEDFMainWindow mainWindow,
                                   PreciseScoring preciseScoring,
                                   boolean isLoading) {
        super(mainWindow, true);
        this.mainWindow = mainWindow;
        this.preciseScoring = preciseScoring;

        getContentPane().add(jTabbedPane);
        jTabbedPane.add(newPanel, JEDFMainWindow.getLocalizedString("New"));
        jTabbedPane.add(loadPanel, JEDFMainWindow.getLocalizedString("Load"));
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        if (isLoading) {
            jTabbedPane.setSelectedComponent(loadPanel);
        }
        else {
            jTabbedPane.setSelectedComponent(newPanel);
        }

        loadPanel.add(jlLoad, BorderLayout.NORTH);
        JPanel tempLoadCenterPanel = new JPanel();
        tempLoadCenterPanel.add(jtfLoad);
        tempLoadCenterPanel.add(jbLoadBrowse);
        loadPanel.add(tempLoadCenterPanel, BorderLayout.CENTER);
        JPanel tempLoadSouthPanel = new JPanel();
        tempLoadSouthPanel.add(jbLoadOk);
        tempLoadSouthPanel.add(jbLoadCancel);
        loadPanel.add(tempLoadSouthPanel, BorderLayout.SOUTH);
        jtfLoad.setColumns(20);

        newPanel.add(jlNew, BorderLayout.NORTH);
        jtfNewFileName.setColumns(20);

        JPanel tempNewSouthPanel = new JPanel();
        tempNewSouthPanel.add(jbNewOk);
        tempNewSouthPanel.add(jbNewCancel);
        newPanel.add(tempNewSouthPanel, BorderLayout.SOUTH);
        jtfNewFileName.setColumns(20);
        jtfNewGranularity.setColumns(3);
        JPanel tempNewCenterPanel = new JPanel();
        tempNewCenterPanel.setLayout(new BoxLayout(tempNewCenterPanel,BoxLayout.Y_AXIS));
        JPanel tempNewSubCenterPanel1 = new JPanel();
        tempNewSubCenterPanel1.add(jtfNewFileName);
        tempNewSubCenterPanel1.add(jbNewBrowse);

        JPanel tempNewSubCenterPanel2 = new JPanel();
        tempNewSubCenterPanel2.add(jlNewGranularity);
        tempNewSubCenterPanel2.add(jtfNewGranularity);

        tempNewCenterPanel.add(tempNewSubCenterPanel1);
        tempNewCenterPanel.add(tempNewSubCenterPanel2);

        newPanel.add(tempNewCenterPanel, BorderLayout.CENTER);

        String str = EDFFileFilter.changeFileExtension(mainWindow.
                getEDFFile().getFile(), ".sf");
        jtfLoad.setText(str);
        jtfNewFileName.setText(str);
        jtfNewGranularity.setText("2");

        addListeners();
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        mainWindow.updatePermissions();
    }

    private void addListeners() {
        jbLoadCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                dispose();
            }
        });

        jbNewCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                dispose();
            }
        });

        jbLoadBrowse.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                File file = new File(jtfNewFileName.getText());
                JFileChooser chooser = new JFileChooser();
                chooser.setSelectedFile(file);

                String[] extensions = {"sf"};
                EDFFileFilter edfFileFilter = new EDFFileFilter(extensions, JEDFMainWindow.
                        getLocalizedString("Precise scoring file"));
                chooser.setFileFilter(edfFileFilter);

                if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                    String chosenFile = chooser.getSelectedFile().
                                        getAbsolutePath();

                    jtfLoad.setText(chosenFile);
                }
            }
        });

        jbNewBrowse.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                File file = new File(jtfNewFileName.getText());
                JFileChooser chooser = new JFileChooser();
                chooser.setSelectedFile(file);

                String[] extensions = {"sf"};
                EDFFileFilter edfFileFilter = new EDFFileFilter(extensions, JEDFMainWindow.
                        getLocalizedString("Precise scoring file"));
                chooser.setFileFilter(edfFileFilter);

                if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                    String chosenFile = chooser.getSelectedFile().
                                        getAbsolutePath();

                    jtfNewFileName.setText(chosenFile);
                }
            }
        });

        jbLoadOk.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                try {
                    preciseScoring.loadPreciseScoring(new File(jtfLoad.getText()));
                    dispose();
                }
                catch (NumberFormatException nfe) {
                    JOptionPane.showMessageDialog(null,JEDFMainWindow.getLocalizedString(
                            "Error : the specified file does not seem to contain precise scoring data."));
                }
                catch (FileNotFoundException e) {
                    JOptionPane.showMessageDialog(null, JEDFMainWindow.getLocalizedString(
                            "Error : please verify that you have specified a correct filename\n") +
                                                  JEDFMainWindow.getLocalizedString(
                            "and that you have write access on it."),
                                                  JEDFMainWindow.getLocalizedString("Error"),
                                                  JOptionPane.ERROR_MESSAGE);
                }
                catch (HypnogramNotLoadedException e) {
                    e.printStackTrace();
                }
                catch (IOException e) {
                    JOptionPane.showMessageDialog(null, JEDFMainWindow.getLocalizedString(
                            "Error : please verify that you have specified a correct Precise Scoring filename\n") +
                                                  JEDFMainWindow.getLocalizedString(
                            "and that you have write access on it."), JEDFMainWindow.
                                                  getLocalizedString("Error"),
                                                  JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        jbNewOk.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                File file = new File(jtfNewFileName.getText());

                if (file.exists()) {
                    int res = JOptionPane.showConfirmDialog(null,
                            JEDFMainWindow.getLocalizedString(
                                    "The specified file already exits.\n") +
                            JEDFMainWindow.getLocalizedString(
                                    "Continuing will erase its content.\nAre you sure you want to continue ?"),
                            JEDFMainWindow.getLocalizedString("Warning"),
                            JOptionPane.YES_NO_OPTION);
                    if (res != JOptionPane.YES_OPTION) {
                        return;
                    }
                    file.delete();
                }

                int granularity = 0;
                try {
                    granularity = new Integer(jtfNewGranularity.getText().trim()).
                                  intValue();
                    if (granularity <= 0) {
                        throw new NumberFormatException();
                    }

                    Cursor hourglassCursor = new Cursor(Cursor.WAIT_CURSOR);
                    setCursor(hourglassCursor);

                    preciseScoring.createPreciseScoring(mainWindow.getEDFFile(),
                            file, granularity);

                    Cursor normalCursor = new Cursor(Cursor.DEFAULT_CURSOR);
                    setCursor(normalCursor);

                    dispose();
                }
                catch (NumberFormatException nfe) {
                    JOptionPane.showMessageDialog(null,
                                                  JEDFMainWindow.
                                                  getLocalizedString(
                            "Error : please input a correct integer value for the granularity."),
                                                  JEDFMainWindow.
                                                  getLocalizedString("Error"),
                                                  JOptionPane.ERROR_MESSAGE);
                }
                catch (HypnogramNotLoadedException e) {
                    e.printStackTrace();
                }
                catch (IOException e) {
                    JOptionPane.showMessageDialog(null, JEDFMainWindow.getLocalizedString(
                            "Error : please verify that you have specified a correct filename\n") +
                                                  JEDFMainWindow.getLocalizedString(
                            "and that you have write access on it."),
                                                  JEDFMainWindow.getLocalizedString("Error"),
                                                  JOptionPane.ERROR_MESSAGE);
                }
            }
        });
    }
}
